/**
 * StudyTimeServicee.java
 * Copyright (c) 2018, 北京科技有限公司版权所有.
*/

package com.sftz.modules.datacollect.analytics.service.Impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

import org.nutz.json.Json;

import com.google.common.io.Resources;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sftz.framework.vendors.elasticsearch.EsSearchUtil;
import com.sftz.modules.datacollect.analytics.dto.BehaviorStudyDto;
import com.sftz.modules.datacollect.analytics.dto.StudyScoreCollectDto;
import com.sftz.modules.datacollect.analytics.dto.UserBehaviorLogDto;
import com.sftz.modules.datacollect.analytics.service.StudyMessageService;
import com.sftz.modules.datacollect.dto.StudyAudioImportDto;
import com.sftz.modules.datacollect.dto.StudyVideoImportDto;
import com.uxuexi.core.common.util.Util;

public class StudyTimeLogServiceImpl implements StudyMessageService {

	/**
	 * @author   杜凯丽
	 * @throws IOException 
	 * @Date	 2018年4月25日
	 *（用途:查询最后一次学习时间）
	 */
	@Override
	public String studyMessage(int courseId, int userId) {
		String indexName = "logstash-study*";
		String tmplPath = "elasticsearch/templates/dukl/log_query_firstDate.js";
		URL url = Resources.getResource(tmplPath);
		String query;
		try {
			query = Resources.toString(url, Charset.forName("utf-8"));
			query = query.replaceAll("@userId", userId + "");
			query = query.replaceAll("@courseId", courseId + "");
			query = query.replaceAll("@from", "0");
			query = query.replaceAll("@size", "1");
			List<UserBehaviorLogDto> lst = EsSearchUtil.searchTmpl(query, indexName, UserBehaviorLogDto.class);
			String reqTime = null;
			if (!Util.isEmpty(lst)) {
				Date studyTime = null;
				String json = Json.toJson(lst);
				Gson gs = new Gson();
				List<UserBehaviorLogDto> jsonListObject = gs.fromJson(json, new TypeToken<List<UserBehaviorLogDto>>() {
				}.getType());
				for (UserBehaviorLogDto userBehaviorLogDto : jsonListObject) {
					studyTime = userBehaviorLogDto.getAccess_time();
				}
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				reqTime = sdf.format(studyTime);
			} else {
				reqTime = "该学生还未开始学习本课程";
			}
			return reqTime;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 开大项目
	 * @author   DuKL
	 * @Date	 2018年8月14日
	 * (effect:用户首次学习时间)
	 */
	@Override
	public String studyFirstTime(int courseId, int userId) {
		String indexName = "logstash-study*";
		String tmplPath = "elasticsearch/templates/dukl/log_query_lastDate.js";
		URL url = Resources.getResource(tmplPath);
		String query;
		try {
			query = Resources.toString(url, Charset.forName("utf-8"));
			query = query.replaceAll("@userId", userId + "");
			query = query.replaceAll("@courseId", courseId + "");
			query = query.replaceAll("@from", "0");
			query = query.replaceAll("@size", "1");
			List<UserBehaviorLogDto> lst = EsSearchUtil.searchTmpl(query, indexName, UserBehaviorLogDto.class);
			String reqTime = null;
			if (!Util.isEmpty(lst)) {
				Date studyTime = null;
				String json = Json.toJson(lst);
				Gson gs = new Gson();
				List<UserBehaviorLogDto> jsonListObject = gs.fromJson(json, new TypeToken<List<UserBehaviorLogDto>>() {
				}.getType());
				for (UserBehaviorLogDto userBehaviorLogDto : jsonListObject) {
					studyTime = userBehaviorLogDto.getAccess_time();
				}
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				reqTime = sdf.format(studyTime);
			} else {
				reqTime = "该学生还未开始学习本课程";
			}
			return reqTime;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 开大项目
	 * @author   DuKL
	 * @Date	 2018年8月14日
	 * (effect:学习视频的总时长-----<视频count,不去重>)
	 */
	@Override
	public double studyTime(int courseId, int userId) {
		List<UserBehaviorLogDto> lst;
		try {
			lst = videoQueryLogJs(courseId, userId);
			double alreadyTime = lst.size();
			alreadyTime = alreadyTime / 60;
			BigDecimal b = new BigDecimal(alreadyTime);
			alreadyTime = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
			return alreadyTime;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}

	/**
	 * 开大项目
	 * @author   DuKL
	 * @Date	 2018年8月14日
	 * (effect:学习音频的总时长-----<音频count,不去重>)
	 */
	@Override
	public double audioTime(int courseId, int userId) {
		List<UserBehaviorLogDto> lst;
		try {
			lst = audioQueryLogJs(courseId, userId);
			double audioTime = lst.size();
			audioTime = audioTime / 60;
			BigDecimal b = new BigDecimal(audioTime);
			audioTime = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
			return audioTime;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}

	/**
	 * 开大项目
	 * @author   DuKL
	 * @Date	 2018年8月14日
	 * (effect:当前课程下已观看的视频时间,去重----<视频id---时长count>)
	 */
	@Override
	public List<StudyScoreCollectDto> studyVideoVid(int courseId, int userId) {
		List<UserBehaviorLogDto> lst;
		try {
			lst = videoQueryLogJs(courseId, userId);
			List<BehaviorStudyDto> items = videoList(lst);
			//转为所需要的list集合
			List<StudyScoreCollectDto> list = new ArrayList<StudyScoreCollectDto>();
			//根据视频id分组统计
			Map<String, Long> sum = items.stream().collect(
					Collectors.groupingBy(BehaviorStudyDto::getVideoId, Collectors.counting()));
			Iterator<Entry<String, Long>> iter = sum.entrySet().iterator(); // 获得map的Iterator
			while (iter.hasNext()) {
				Entry<String, Long> entry = iter.next();
				Long value = entry.getValue();
				Integer timeCount = new Long(value).intValue();
				StudyScoreCollectDto studyScoreCollectDto = new StudyScoreCollectDto();
				studyScoreCollectDto.setVid(entry.getKey());
				studyScoreCollectDto.setTimeCount(timeCount);
				list.add(studyScoreCollectDto);
			}
			return list;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 开大项目
	 * @author   DuKL
	 * @Date	 2018年8月14日
	 * (effect:当前课程下已观看的音频时间,去重----<音频id---时长count>)
	 */
	@Override
	public List<StudyScoreCollectDto> studyaudioVid(int courseId, int userId) {
		List<UserBehaviorLogDto> lst;
		try {
			lst = audioQueryLogJs(courseId, userId);
			List<BehaviorStudyDto> items = audioList(lst);
			//转为所需要的list集合
			List<StudyScoreCollectDto> list = new ArrayList<StudyScoreCollectDto>();
			//根据视频id分组统计
			Map<String, Long> sum = items.stream().collect(
					Collectors.groupingBy(BehaviorStudyDto::getAudioId, Collectors.counting()));
			Iterator<Entry<String, Long>> iter = sum.entrySet().iterator(); // 获得map的Iterator
			while (iter.hasNext()) {
				Entry<String, Long> entry = iter.next();
				Long value = entry.getValue();
				Integer timeCount = new Long(value).intValue();
				StudyScoreCollectDto studyScoreCollectDto = new StudyScoreCollectDto();
				studyScoreCollectDto.setAudioId(entry.getKey());
				studyScoreCollectDto.setTimeCount(timeCount);
				list.add(studyScoreCollectDto);
			}
			return list;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 开大项目
	 * @author   DuKL
	 * @Date	 2018年8月14日
	 * (effect:用户观看的视频详情去重后)
	 */
	@Override
	public List<BehaviorStudyDto> studyVideo(int courseId, int userId) {
		List<UserBehaviorLogDto> lst;
		try {
			lst = videoQueryLogJs(courseId, userId);
			List<BehaviorStudyDto> items = videoList(lst);
			return items;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}

	/**
	 * 开大项目
	 * @author   DuKL
	 * @Date	 2018年8月14日
	 * (effect:询用户对音频观看的详情记录----<视频id---观看time--去重后>)
	 */
	@Override
	public List<BehaviorStudyDto> studyAudio(int courseId, int userId) {
		List<UserBehaviorLogDto> lst;
		try {
			lst = audioQueryLogJs(courseId, userId);
			List<BehaviorStudyDto> items = audioList(lst);
			return items;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 开大项目
	 * @author   DuKL
	 * @Date	 2018年8月14日
	 * (effect:将视频日志查询出来的json转换为List)
	 */
	public List<BehaviorStudyDto> videoList(List<UserBehaviorLogDto> lst) {
		List<BehaviorStudyDto> items = new ArrayList<BehaviorStudyDto>();
		String json = Json.toJson(lst);
		Gson gs = new Gson();
		List<UserBehaviorLogDto> jsonListObject = gs.fromJson(json, new TypeToken<List<UserBehaviorLogDto>>() {
		}.getType());
		for (UserBehaviorLogDto userBehaviorLogDto : jsonListObject) {
			Integer remote_user = userBehaviorLogDto.getRemote_user();
			StudyVideoImportDto studyDto = gs.fromJson(Json.toJson(userBehaviorLogDto.getRequest_params()),
					StudyVideoImportDto.class);
			BehaviorStudyDto behaviorStudyDto = new BehaviorStudyDto();
			behaviorStudyDto.setUserId(remote_user);
			behaviorStudyDto.setVideoId(studyDto.getVid());
			//behaviorStudyDto.setTime(Integer.parseInt(studyDto.getTime()));
			Double douNum = Double.valueOf(studyDto.getTime());
			int intNum = douNum.intValue();
			behaviorStudyDto.setTime(intNum);
			items.add(behaviorStudyDto);
		}
		//去掉list里的重复数据
		HashSet<BehaviorStudyDto> h = new HashSet<BehaviorStudyDto>(items);
		items.clear();
		items.addAll(h);
		//按照观看秒数进行排序
		Collections.sort(items, new Comparator<BehaviorStudyDto>() {
			@Override
			public int compare(BehaviorStudyDto o1, BehaviorStudyDto o2) {
				int i = o1.getTime() - o2.getTime();
				if (i == 0) {
					return o1.getTime() - o2.getTime();
				}
				return i;
			}
		});
		return items;
	}

	/**
	 * 开大项目
	 * @author   DuKL
	 * @Date	 2018年8月14日
	 * (effect:将音频日志查询出来的json转换为List)
	 */
	public List<BehaviorStudyDto> audioList(List<UserBehaviorLogDto> lst) {
		List<BehaviorStudyDto> items = new ArrayList<BehaviorStudyDto>();
		String json = Json.toJson(lst);
		Gson gs = new Gson();
		List<UserBehaviorLogDto> jsonListObject = gs.fromJson(json, new TypeToken<List<UserBehaviorLogDto>>() {
		}.getType());
		for (UserBehaviorLogDto userBehaviorLogDto : jsonListObject) {
			Integer remote_user = userBehaviorLogDto.getRemote_user();
			StudyAudioImportDto studyDto = gs.fromJson(Json.toJson(userBehaviorLogDto.getRequest_params()),
					StudyAudioImportDto.class);
			BehaviorStudyDto behaviorStudyDto = new BehaviorStudyDto();
			behaviorStudyDto.setUserId(remote_user);
			behaviorStudyDto.setAudioId(studyDto.getAudioId());
			Double douNum = Double.valueOf(studyDto.getTime());
			int intNum = douNum.intValue();
			behaviorStudyDto.setTime(intNum);
			//behaviorStudyDto.setTime(Integer.parseInt(studyDto.getTime()));
			items.add(behaviorStudyDto);
		}
		//去掉list里的重复数据
		HashSet<BehaviorStudyDto> h = new HashSet<BehaviorStudyDto>(items);
		items.clear();
		items.addAll(h);
		//按照观看秒数进行排序
		Collections.sort(items, new Comparator<BehaviorStudyDto>() {
			@Override
			public int compare(BehaviorStudyDto o1, BehaviorStudyDto o2) {
				int i = o1.getTime() - o2.getTime();
				if (i == 0) {
					return o1.getTime() - o2.getTime();
				}
				return i;
			}
		});
		return items;
	}

	/**
	 * 开大项目
	 * @author   DuKL
	 * @throws IOException 
	 * @Date	 2018年8月14日
	 * (effect:视频学习记录所要查询的log.js)
	 */
	public List<UserBehaviorLogDto> videoQueryLogJs(int courseId, int userId) throws IOException {
		String indexName = "logstash-study*";
		String tmplPath = "elasticsearch/templates/dukl/log_query_videoTime.js";
		URL url = Resources.getResource(tmplPath);
		String query = Resources.toString(url, Charset.forName("utf-8"));
		query = query.replaceAll("@userId", userId + "");
		query = query.replaceAll("@courseId", courseId + "");
		List<UserBehaviorLogDto> lst = EsSearchUtil.searchTmpl(query, indexName, UserBehaviorLogDto.class);
		return lst;
	}

	/**
	 * 开大项目
	 * @author   DuKL
	 * @Date	 2018年8月14日
	 * (effect:音频学习记录所要查询的log.js)
	 */
	public List<UserBehaviorLogDto> audioQueryLogJs(int courseId, int userId) throws IOException {
		String indexName = "logstash-study*";
		String tmplPath = "elasticsearch/templates/dukl/log_query_audioTime.js";
		URL url = Resources.getResource(tmplPath);
		String query = Resources.toString(url, Charset.forName("utf-8"));
		query = query.replaceAll("@userId", userId + "");
		query = query.replaceAll("@courseId", courseId + "");
		List<UserBehaviorLogDto> lst = EsSearchUtil.searchTmpl(query, indexName, UserBehaviorLogDto.class);
		return lst;
	}
}
